package cn.you.GenghisKhan.config;

import cn.you.GenghisKhan.common.extension.Adaptive;
import cn.you.GenghisKhan.common.jdbc.JDBCMySql;
import cn.you.GenghisKhan.common.utils.StringUtils;
import cn.you.GenghisKhan.config.bean.AppBean;
import cn.you.GenghisKhan.config.utils.GlobalConfig;
import cn.you.GenghisKhan.db.relation.bean.DatabaseBean;
import cn.you.GenghisKhan.db.relation.bean.TenantBean;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

@Adaptive
public class MysqlConfigCentare extends AbstractConfigCentre {
    private static final Logger logger = LoggerFactory.getLogger(MysqlConfigCentare.class);

    private JDBCMySql jdbcMySql;

    public MysqlConfigCentare() {
        jdbcMySql = new JDBCMySql(GlobalConfig.getConfig("mysql.url"));
    }

    @Override
    List<TenantBean> createTenantBeans() {
        return null;
    }

    @Override
    DatabaseBean createDatabaseBean(String tag) {
        String sql = "select name,db_type as dbType,host,port,username,IFNULL(`password`,'') as password,initialSize,maxActive,minIdle,maxWait from relation where name='" + tag + "'";
        DatabaseBean databaseBean = null;
        try {
            databaseBean = jdbcMySql.getObject(DatabaseBean.class, sql);
        } catch (Exception e) {
            logger.error("配置中心（Mysql）读取DatabaseBean异常:{}", e.getMessage());
        }
        return databaseBean;
    }

    @Override
    Map<String, DatabaseBean> createDatabaseBeanMap() {
        return null;
    }

    @Override
    AppBean createAppBean(String appName) {
        String sql = "select app_name as appName ,rpc_port as rpcPort,rpc_protocol as rpcProtocol,rpc_scan as rpcScan,rpc_timeout as rpcTimeout,tomcat_port as tomcatPort,tomcat_maxConnections as tomcatMaxconnections,tomcat_acceptCount as tomcatAcceptcount,\n" +
                "tomcat_maxThreads as tomcatMaxthreads,tomcat_minSpareThreads as tomcatMinsparethreads,tomcat_connectionTimeout as tomcatConnectiontimeout,\n" +
                "relation_def as relationDef,zk_address as zkAddress,properties  from service where app_name='" + appName + "'";
        AppBean appBean = null;
        try {
            appBean = jdbcMySql.getObject(AppBean.class, sql);
            if (appBean != null &&
                    !StringUtils.isEmpty(appBean.getProperties())
                    ) {
                Map<String, Object> params = JSON.parseObject(appBean.getProperties(), Map.class);
                appBean.setParams(params);
            }
        } catch (Exception e) {
            logger.error("配置中心（Mysql）读取AppBean异常:{}", e.getMessage());
        }
        return appBean;
    }
}
